package com.nwpu.hass.utils;

import com.nwpu.hass.domain.DeviceEntity;
import com.nwpu.hass.repository.DeviceRepository;
import com.nwpu.hass.service.DeviceService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author alecHe
 * @desc 定时检查设备的情况,每个月检查一次
 *      提供估计设备劳损状态的算法服务
 * @date 2021-01-12 15:08:48
 */
@Component
public class ScheduleCheckDevice {

    @Resource
    private DeviceRepository deviceRepository;
    @Resource
    private DeviceService deviceService;

    private static final double BrokenRate = 80;

    @Scheduled(cron = "0 0 8 15 * ?")
    private void cancelTimeOutOrder() throws Exception {

        int loop_max = 2;

        StringBuilder deviceIds = new StringBuilder();
        StringBuilder sub_deviceIds = new StringBuilder();
        List<DeviceEntity> devices = deviceRepository
                .findByStatusAndUsedTimesGreaterThan(0,1);

        for(DeviceEntity deviceEntity:devices){
            if(isBroken(deviceEntity)){
                if(loop_max > 0){
                    sub_deviceIds.append(deviceEntity.getDeviceId()).append(",");
                }
                deviceIds.append(deviceEntity.getDeviceId()).append(",");
                //将设备状态置为废弃状态
                deviceEntity.setStatus(Status.DEAD.getStatus());
                deviceRepository.save(deviceEntity);
                loop_max--;
            }
        }

        if(!"".equals(deviceIds.toString())){
            //删除多余的逗号
            deviceIds.deleteCharAt(deviceIds.length()-1);
            sub_deviceIds.deleteCharAt(sub_deviceIds.length()-1);

            deviceService.sendMailAndWeChat(deviceIds.substring(0,deviceIds.length()));

        }

    }

    /**
     * 故障预警算法
     * cost*usedYear/usedTimes计算的是这个设备的效用，太低了被评估为报废
     * @return 是否出现故障
     */
    public static Boolean isBroken(DeviceEntity deviceEntity){
        double cost = deviceEntity.getCost();
        int usedTimes = deviceEntity.getUsedTimes();
        int usedYear = deviceEntity.getUsedYear();
        if(usedTimes == 0){
            return false;
        }
        return cost*usedYear/usedTimes < BrokenRate;
    }

}
